package com.wuxinwudai.android.app;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Looper;
import android.util.Log;

import com.wuxinwudai.android.util.RegexUtils;

import java.lang.Thread.UncaughtExceptionHandler;


/**
 * CrashHandler 类为应用奔溃异常处理程序类
 * @author 吾心无待 于 2016年7月19日
 */
public class CrashHandler implements UncaughtExceptionHandler {
    //调试标识
    private static final String TAG = "CrashHandler";
    //单例
    private static CrashHandler mHandler = new CrashHandler();
    private CrashReporter reporter;
    /**
     * 私有构造函数
     */
    private CrashHandler(){		
    }
    /**
     * 单例返回 CrashHandler
     * @return CrashHandler 实例
     */
    public static CrashHandler getInstance(){
       return mHandler;
    }
    /**
     * 获取 CrashReporter 对象
     * @return
     */
    public CrashReporter getCrashReporter(){
    	if(reporter == null){
            if(AppConfig.REPORT_EXCEPTION_EMAIL == null) Log.d(TAG,"使用 DefaultCrashReporter 但未配置 AppConfig.REPORT_EXCEPTION_EMAIL");
    		reporter = new DefaultCrashReporter();
    	}
    	return reporter;
    }
    /**
     * 设置 CrashReporter 对象
     * @param reporter
     */
    public void setCrashReporter(CrashReporter reporter){
    	this.reporter = reporter;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        String threadName = thread.getName();
        Log.d(TAG, "未捕获异常,线程:"+thread + "  线程名称:"+ threadName
                +"  id:"+thread.getId() + "  exception:"+ex);
        if("main".equals(threadName)){
            Log.d(TAG,"主线程崩溃!");
        }else{
            Log.d(TAG, "子线程崩溃!");
        }
        final StringBuffer exceptionStr = new StringBuffer();
        final Context context = ActivityCollector.getCurrentActivity();
        if(context != null){
            Log.d(TAG, "Activity:" + context.getClass().getName());
            try{
                PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(),0);
                exceptionStr.append("Version: " + pinfo.versionName + "(" + pinfo.versionCode + ")\n");
                exceptionStr.append("Android: " + android.os.Build.VERSION.RELEASE + "(" + android.os.Build.MODEL + ")\n");
                exceptionStr.append("Exception: " + ex.getMessage() + "\n");
            }catch (PackageManager.NameNotFoundException e){

            }
            StackTraceElement[] elements = ex.getStackTrace();
            for (int i = 0; i < elements.length; i++) {
                exceptionStr.append(elements[i].toString() + "\n");
            }
            Log.d(TAG, exceptionStr.toString());
            if (!RegexUtils.isEmail(AppConfig.REPORT_EXCEPTION_EMAIL)) {
                Log.d(TAG,"发送邮件 mailTo参数 不是合法Email格式");
            }
            else{
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        getCrashReporter().report(context, AppConfig.REPORT_EXCEPTION_EMAIL, exceptionStr.toString());
                        Looper.loop();
                    }
                }).start();
            }
        }	
        else{
        	Log.d(TAG, "Exception happened before activity was created");
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
}
